﻿using GalaSoft.MvvmLight.Messaging;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace VisionApp.Interface
{
    public interface ICfgIO
    {
        int Load<T>(string name, ref T obj);
        int Save<T>(string name, T obj);
    }

    public class CfgIO: ICfgIO
    {
        public int Load<T>(string name, ref T obj)
        {
            string path = AppDomain.CurrentDomain.BaseDirectory + "Config\\" + name + ".json";
            if (System.IO.File.Exists(path))
            {

                using (StreamReader sr = new StreamReader(path, Encoding.Default, false))
                {
                    string msg = sr.ReadToEnd();
                    obj = JsonConvert.DeserializeObject<T>(msg);
                    sr.Close();
                    sr.Dispose();
                }
                return 0;
            }
            else
            {
                FileStream fs = File.Create(path);
                fs.Close();
                return -1;
            }
        }

        public int Save<T>(string name, T obj)
        {
            string path = AppDomain.CurrentDomain.BaseDirectory+"Config\\"+name+".json";
            if (!File.Exists(path))
            {
                FileStream fs = File.Create(path);
                fs.Close();
            }
            if (File.Exists(path))
            {
                using (StreamWriter sw = new StreamWriter(path, false, Encoding.Default))
                {
                    sw.Write(JsonConvert.SerializeObject(obj));
                    sw.Close();
                    sw.Dispose();
                }
                return 0;
            }
            else
            {
                Messenger.Default.Send<string>("No "+ obj.ToString()+ " Found!");
                return -1;
            }
        }
    }
}
